package com.lbd.commons.interceptor;

import com.lbd.commons.ApplicationContextUtil;
import com.lbd.system.bean.Employee;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by WangYajie on 2016/9/12.
 */

public class TokenInterceptor implements HandlerInterceptor {
    private final Logger log = Logger.getLogger(this.getClass());
    private Set<String> noLogin = new HashSet<>(
            Arrays.asList("/statistics/showLine", "/", "/employee/login", "/var/imgCode", "/employee/logout"));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = (Employee) request.getSession().getAttribute(Employee.SESSION_USER);
        String uri = request.getRequestURI();
        log.info(uri);
        if (employee == null && !noLogin.contains(uri)) {
            response.setStatus(499);
            response.getWriter().print("用户未登录");
            return false;
        }
        String token = request.getHeader("token");
        String dev = ApplicationContextUtil.applicationContext.getEnvironment().getProperty("dev");
        if ("true".equals(dev)) {
            log.info("正在以开发模式运行");
            return true;
        }
        log.info(token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws UnsupportedOperationException {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws UnsupportedOperationException {

    }
}
